<template>
    <div>
        <el-card>
            <el-row :gutter="20">
                <el-col :span="6">
                    <h4 class="textAlign">项目名称：{{ projectName }}</h4>
                </el-col>
                <el-col :span="6">
                    <h4 class="textAlign">项目编号：{{ projectNo }}</h4>
                </el-col>
                <el-col :span="6">
                    <h4 class="textAlign">项目阶段：{{ projectStage }}</h4>
                </el-col>
                <el-col :span="6">
                    <div style="text-align: right">
                        <el-button size="mini" type="primary" @click="handleSetting">设置</el-button>
                        <el-button size="mini" type="primary">刷新</el-button>
                        <el-button size="mini" @click="goBack">返回</el-button>
                    </div>
                </el-col>
            </el-row>
        </el-card>
        <el-card class="card-margin">
            <h4 class="textAlign">框图信息</h4>
            <div class="container card-margin">
                <el-card class="box-card cardItem" v-for="(card, idx) in listData" :key="idx">
                    <template #header>
                        <div class="card-header">
                            <span>{{ card.name }}</span>
                        </div>
                    </template>
                    <el-progress
                        :text-inside="true"
                        :stroke-width="24"
                        :percentage="card.percentage"
                        status="success"
                    />
                    <el-row class="card-margin">
                        <el-col :span="18" class="textAlign">框图名称</el-col>
                        <el-col :span="6" class="textAlign">状态</el-col>
                    </el-row>
                    <el-table
                        :data="card.ppcgBlockDiagarmDtlList"
                        :show-header="false"
                        style="width: 100%"
                        @row-click="rowClick"
                    >
                        <el-table-column prop="titleName" label="框图名称" width="180">
                            <template #default="scope">
                                <div>{{ scope.row.titleName }}({{ scope.row.count }}/{{ scope.row.count }})</div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="state" label="状态" />
                    </el-table>
                </el-card>
            </div>
        </el-card>
        <el-dialog v-model="dialogFormVisible" title="设置表单">
            <el-form :model="form" :rules="rules" ref="ruleForm">
                <el-form-item label="框图列表" :label-width="formLabelWidth" prop="listName">
                    <el-select
                        style="width: 100%"
                        v-model="form.listName"
                        placeholder="请选择框图列表"
                        @change="handleSelectList"
                    >
                        <el-option
                            :label="item.name"
                            :value="item"
                            :key="idx"
                            v-for="(item, idx) in listData"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="表单名称" :label-width="formLabelWidth" prop="titleName">
                    <el-select
                        v-model="form.titleName"
                        style="width: 100%"
                        placeholder="请选择表单名称"
                        @change="handleTitle"
                    >
                        <el-option
                            :label="item.titleName"
                            :value="item"
                            :key="idx"
                            v-for="(item, idx) in formData"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <div v-if="form.isTitle === '否'">
                    <el-form-item label="设置周期" :label-width="formLabelWidth" prop="date">
                        <el-date-picker
                            style="width: 100%"
                            v-model="form.date"
                            type="daterange"
                            value-format="YYYY-MM-DD"
                            range-separator="-"
                            @focus="handleDateFocus"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                        ></el-date-picker>
                    </el-form-item>
                    <el-form-item label="设置频次" :label-width="formLabelWidth" prop="frequency">
                        <div style="display: flex">
                            <el-select
                                v-model="form.frequency"
                                placeholder="请选择设置频次"
                                style="width: 30%"
                                @change="handleChangeFrequency"
                                @visible-change="handleSelect"
                            >
                                <el-option
                                    v-for="(frequency, index) in frequencyList"
                                    :key="index"
                                    :label="frequency"
                                    :value="frequency"
                                ></el-option>
                            </el-select>
                            <el-checkbox
                                v-if="form.frequency === '按周'"
                                style="margin: 0 1rem; width: 7%"
                                v-model="form.frequency2"
                                label="每天"
                                @change="handleCheckBox"
                            ></el-checkbox>
                            <el-select
                                v-if="form.frequency === '按周'"
                                multiple
                                v-model="form.frequency3"
                                placeholder="请选择频次"
                                style="width: 63%"
                                @change="handleMultipleSelect"
                                @remove-tag="handleRemoveTag"
                                value-key="val"
                            >
                                <el-option
                                    v-for="(item, index) in frequencyCycleList"
                                    :key="index"
                                    :label="item.label"
                                    :value="item"
                                ></el-option>
                            </el-select>
                            <!-- 按月 -->
                            <div
                                v-if="form.frequency === '按月'"
                                style="text-align: left; margin-left: 2rem"
                            >
                                <el-radio label="day" v-model="radioMouth" @change="handleRadio">
                                    <span style="margin-right: 0.5rem">每</span>
                                    <el-input
                                        v-model="form.frequency2Day"
                                        style="width: 5rem; margin-right: 0.5rem"
                                    ></el-input>
                                    <span style="margin-right: 0.5rem">个月的第</span>
                                    <el-select
                                        style="margin-right: 0.5rem"
                                        v-model="form.frequency3Day"
                                    >
                                        <el-option :label="i" :value="i" v-for="i in 31"></el-option>
                                    </el-select>
                                    <span>天</span>
                                </el-radio>
                                <el-radio label="week" v-model="radioMouth" @change="handleRadio">
                                    <span style="margin-right: 0.5rem">每</span>
                                    <el-input
                                        v-model="form.frequency2Week"
                                        style="width: 5rem; margin-right: 0.5rem"
                                    ></el-input>
                                    <span style="margin-right: 0.5rem">个月的第</span>
                                    <el-select
                                        style="margin-right: 0.5rem"
                                        v-model="form.frequency3Week"
                                    >
                                        <el-option :label="i" :value="i" :key="i" v-for="i in 5"></el-option>
                                        <el-option label="最后一个" :value="6"></el-option>
                                    </el-select>
                                    <span style="margin-right: 0.5rem">个</span>
                                    <el-select
                                        style="margin-right: 0.5rem"
                                        v-model="form.frequency4Week"
                                    >
                                        <el-option
                                            :label="'星期' + i"
                                            :value="i"
                                            :key="i"
                                            v-for="i in 7"
                                        ></el-option>
                                    </el-select>
                                </el-radio>
                            </div>

                            <!-- 按年 -->
                            <div
                                v-if="form.frequency === '按年'"
                                style="text-align: left; margin-left: 2rem"
                            >
                                <el-radio label="day" v-model="radioYear" @change="handleRadio">
                                    <span style="margin-right: 0.5rem">每年</span>
                                    <el-select
                                        style="margin-right: 0.5rem; width: 10rem"
                                        v-model="form.frequency2Day"
                                    >
                                        <el-option :label="i" :value="i" v-for="i in 12"></el-option>
                                    </el-select>
                                    <span style="margin-right: 0.5rem">月</span>
                                    <el-select
                                        style="margin-right: 0.5rem; width: 10rem"
                                        v-model="form.frequency3Day"
                                    >
                                        <el-option :label="i" :value="i" v-for="i in 31"></el-option>
                                    </el-select>
                                    <span>日</span>
                                </el-radio>
                                <el-radio label="week" v-model="radioYear" @change="handleRadio">
                                    <span style="margin-right: 0.5rem">每年</span>
                                    <el-select
                                        style="margin-right: 0.5rem; width: 10rem"
                                        v-model="form.frequency2Week"
                                    >
                                        <el-option :label="i" :value="i" v-for="i in 12"></el-option>
                                    </el-select>
                                    <span style="margin-right: 0.5rem">月第</span>
                                    <el-select
                                        style="margin-right: 0.5rem; width: 10rem"
                                        v-model="form.frequency3Week"
                                    >
                                        <el-option :label="i" :value="i" v-for="i in 5"></el-option>
                                        <el-option label="最后一个" :value="6"></el-option>
                                    </el-select>
                                    <span style="margin-right: 0.5rem">个</span>
                                    <el-select
                                        style="margin-right: 0.5rem; width: 10rem"
                                        v-model="form.frequency4Week"
                                    >
                                        <el-option :label="'星期' + i" :value="i" v-for="i in 7"></el-option>
                                    </el-select>
                                </el-radio>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item label="设置次数" :label-width="formLabelWidth" prop="count">
                        <el-input v-model="form.count" disabled></el-input>
                    </el-form-item>
                </div>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleCommit('ruleForm')">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        // 设置频次必填验证
        const validateFrequency = (rule, value, callback) => {
            if (this.form.frequency === "按周") {
                if (this.form.frequency2.length === 0 && this.form.frequency3.length === 0) {
                    callback(new Error("请选择设置频次"));
                } else {
                    callback();
                }
            } else if (this.form.frequency === "按月") {
                if (
                    this.radioMouth === "day" &&
                    (this.form.frequency2Day === "" || this.form.frequency3Day === "")
                ) {
                    callback(new Error("请选择设置频次"));
                } else if (
                    this.radioMouth === "week" &&
                    (this.form.frequency2Week === "" ||
                        this.form.frequency3Week === "" ||
                        this.form.frequency4Week === "")
                ) {
                    callback(new Error("请选择设置频次"));
                }
            } else if (this.form.frequency === "按年") {
                if (
                    this.radioYear === "day" &&
                    (this.form.frequency2Day === "" || this.form.frequency3Day === "")
                ) {
                    callback(new Error("请选择设置频次"));
                } else if (
                    this.radioYear === "week" &&
                    (this.form.frequency2Week === "" ||
                        this.form.frequency3Week === "" ||
                        this.form.frequency4Week === "")
                ) {
                    callback(new Error("请选择设置频次"));
                }
            } else {
                callback();
            }
        };
        return {
            dialogFormVisible: false,
            formLabelWidth: "150px",
            frequencyList: ["按周", "按月", "按年"],
            frequencyCycleList: [],
            form: {
                listName: "",
                titleName: "",
                date: "",
                frequency: [],
                frequency2: [],
                frequency3: [],
                frequency2Day: "",
                frequency3Day: "",
                frequency2Week: "",
                frequency3Week: "",
                frequency4Week: "",
                count: "",
            },
            rules: {
                listName: [
                    {
                        required: true,
                        message: "请选择框图列表",
                        trigger: "change",
                    },
                ],
                titleName: [
                    {
                        required: true,
                        message: "请选择表单名称",
                        trigger: "change",
                    },
                ],
                date: [
                    {
                        required: true,
                        message: "请选择设置周期",
                        trigger: "change",
                    },
                ],
                frequency: [
                    {
                        required: true,
                        validator: validateFrequency,
                        trigger: "change",
                    },
                ],
            },
            radioMouth: "day",
            radioYear: "day",
            listData: [],
            formData: [],
            dataList: [],
        };
    },
    setup() {
        const tableData = [
            {
                name: "项目立项",
                url:
                    "http://pur.ppcg.com.cn/ppcgui/form/formCustSql/view/formCustSqlView.html?code=ppcgLoiProjectVo",
                state: "已完成",
            },
            {
                name: "项目预算",
                url:
                    "http://pur.ppcg.com.cn/ppcgui/form/formCustSql/view/formCustSqlView.html?code=ppcgBudgetProcessingMaster",
                state: "已完成",
            },
            {
                name: "项目现金流V1",
                url:
                    "http://pur.ppcg.com.cn/ppcgui/form/formCustSql/view/formCustSqlView.html?code=ppcgCashFlow2",
                state: "已完成",
            },
            {
                name: "项目现金流V2",
                url:
                    "http://pur.ppcg.com.cn/ppcgui/form/formCustSql/view/formCustSqlView.html?code=ppcgCashFlow2_2",
                state: "已完成",
            },
            {
                name: "项目现金流V3",
                url:
                    "http://pur.ppcg.com.cn/ppcgui/form/formCustSql/view/formCustSqlView.html?code=ppcgCashFlow2_3",
                state: "已完成",
            },
            {
                name: "项目现金流V4",
                url:
                    "http://pur.ppcg.com.cn/ppcgui/form/formCustSql/view/formCustSqlView.html?code=ppcgCashFlow2_4",
                state: "已完成",
            },
            {
                name: "项目现金流V5",
                url:
                    "http://pur.ppcg.com.cn/ppcgui/form/formCustSql/view/formCustSqlView.html?code=ppcgCashFlow2_5",
                state: "已完成",
            },
            {
                name: "项目规划",
                url:
                    "http://pur.ppcg.com.cn/ppcgui/form/formCustSql/view/formCustSqlView.html?code=ppcgPurPlanMaster",
                state: "已完成",
            },
            {
                name: "项目招采流程",
                url:
                    "http://pur.ppcg.com.cn/ppcgui/project/ppcgSupplierManageinfo/ppcgBiddingProcurementProcessList.html?userType=1",
                state: "已完成",
            },
            {
                name: "合同清单",
                url:
                    "http://pur.ppcg.com.cn/ppcgui/form/formCustSql/view/formCustSqlView.html?code=ppcgSevericeContract",
                state: "已完成",
            },
        ];
    },
    created() {
        this.projectNo = this.$route.params.projectNo;
        this.projectName = this.$route.params.projectName;
        this.system = this.$route.params.system;
        this.getDataBySystem();
    },
    methods: {
        // 根据系统查询框图主表子增id
        getDataBySystem() {
            let param = {
                curPage: 1,
                pageSize: 10,
                params: {
                    queryData: [
                        { name: "system_name_", con: "=", val: this.system },
                        { name: "state_", con: "=", val: "启用" },
                    ],
                },
            };
            this.$axios
                .post(`/form/formCustSql/view/list_ppcgBlockDiagramMst`, param)
                .then((res) => {
                    if (res.isOk) {
                        let newData = res.data.list;
                        if (newData.length > 0) this.getDataById(newData[0].id_);
                    } else {
                        this.$ElMessage({
                            message: res.msg,
                            type: "error",
                        });
                    }
                });
        },
        // 根据主表子增id查询详情
        getDataById(id) {
            this.$axios
                .post(`/form/formDefData/getData?key=ppcgBlockDiagarm&id=${id}&isReadOnly=false`)
                .then((res) => {
                    if (res.isOk) {
                        let newData = res.data.data.ppcgBlockDiagarm;
                        this.dataList = newData;
                        this.listData = newData.ppcgBlockDiagarmListDtlList;
                        this.listData.map((d) => {
                            if (d.ppcgBlockDiagarmDtlList) {
                                // 暂时将状态设置成已完成，后期有状态删除
                                d.ppcgBlockDiagarmDtlList.map((dtl) => (dtl.state = "已完成"));
                                // 筛选状态为已完成的数据
                                let percentageData = d.ppcgBlockDiagarmDtlList.filter(
                                    (dtl) => dtl.state === "已完成"
                                );
                                // 计算进度
                                d.percentage =
                                    (percentageData.length / d.ppcgBlockDiagarmDtlList.length).toFixed(2) *
                                    100;
                            }
                        });
                    } else {
                        this.$ElMessage({
                            message: res.msg,
                            type: "error",
                        });
                    }
                });
        },
        // 选择框图列表
        handleSelectList(item) {
            this.formData = item.ppcgBlockDiagarmDtlList;
        },
        handleTitle(item) {
            this.form.titleName = item.titleName;
            this.form.id = item.id;
            this.form.masterId = item.masterId;
            this.form.isTitle = item.isTitle;
            if (item.isTitle === "是") {
                this.dialogFormVisible = false;
                this.$ElMessage({
                    message: "该表单为标题表单，不需要设置周期",
                    type: "success",
                });
            }
        },
        rowClick(row, column, event) {
            const account = localStorage.getItem("account");
            this.$axios.post(`/org/login/valid_oa?account=${account}`).then((res) => {
                if (res.isOk) {
                    // 打开新的标签页
                    window.open(row.url);
                } else {
                    this.$ElMessage({
                        message: res.msg,
                        type: "error",
                    });
                }
            });
        },
        // 设置
        handleSetting() {
            this.dialogFormVisible = true;
        },
        handleDateFocus() {
            if (!this.form.listName) {
                this.$ElMessage({
                    message: "请先选择框图列表",
                    type: "warning",
                });
                return;
            }
            if (!this.form.titleName) {
                this.$ElMessage({
                    message: "请先选择表单名称",
                    type: "warning",
                });
                return;
            }
        },
        handleCheckBox(val) {
            if (val) {
                this.form.frequency3 = this.frequencyCycleList;
                let startTime = this.form.date[0];
                let endTime = this.form.date[1];
                this.form.count = this.$moment(endTime).diff(startTime, "days") + 1; // 拿到开始时间和结束时间天数差 + 1为总天数
            } else {
                this.form.frequency3 = "";
                this.form.count = 0;
            }
        },
        // 按周选择星期几
        handleMultipleSelect(val) {
            this.form.frequency3 = val;
            let startTime = this.form.date[0];
            let endTime = this.form.date[1];
            // 拿到开始时间和结束时间的时间差
            let diffCount = this.$moment(endTime).diff(startTime, "days");
            // 开始时间和结束时间时间差不包含开始时间当天，所以+1天
            diffCount++;
            // 计算有几个完整星期
            let weekCount = parseInt(diffCount / 7);
            let startTimeIsWeek = this.$moment(startTime).isoWeekday();
            let endTimeIsWeek = this.$moment(endTime).isoWeekday();
            let count = 0;
            val.map((v) => {
                // 如果选中的时间在开始和结束时间之内，+1
                if (v.val > startTimeIsWeek || v.val < endTimeIsWeek) {
                    let newWeekCount = weekCount + 1;
                    count += newWeekCount;
                }
                // if选中时间大于结束时间，-1
                if (v.val > endTimeIsWeek) {
                    count--;
                }
            });
            this.form.count = count;
        },
        // 多选移除tag，移除后checkbox取消选中
        handleRemoveTag(val) {
            if (this.form.frequency3.length != this.frequencyCycleList.length) {
                this.form.frequency2 = false;
                this.form.count = this.form.frequency3.length;
            }
        },
        // 刷新
        handleRefresh() { },
        goBack() {
            this.$router.go(-1);
        },
        // 下拉框出现/隐藏时触发
        handleSelect(val) {
            if (!this.form.date && val) {
                this.frequencyList = [];
                this.$ElMessage({
                    message: "请先设置周期",
                    type: "warning",
                });
                return;
            } else {
                this.frequencyList = ["按周", "按月", "按年"];
            }
        },
        // 选择频次
        handleChangeFrequency(val) {
            let startIdx = 0,
                endIdx = 0,
                startTime = "",
                endTime = "",
                frequencyCycleList = [];
            startTime = this.form.date[0];
            endTime = this.form.date[1];
            this.form.frequency2Day = "";
            this.form.frequency3Day = "";
            this.form.frequency2Week = "";
            this.form.frequency3Week = "";
            this.form.frequency4Week = "";
            if (val === "按周") {
                startIdx = this.$moment(startTime).isoWeekday();
                endIdx = this.$moment(endTime).isoWeekday();
                let arrWeek = [
                    { label: "星期一", val: 1 },
                    { label: "星期二", val: 2 },
                    { label: "星期三", val: 3 },
                    { label: "星期四", val: 4 },
                    { label: "星期五", val: 5 },
                    { label: "星期六", val: 6 },
                    { label: "星期日", val: 7 },
                ];
                for (let i = startIdx - 1; i <= endIdx - 1; i++) {
                    frequencyCycleList.push(arrWeek[i]);
                }
                if (this.$moment(endTime).diff(this.$moment(startTime), "days") > 7) {
                    frequencyCycleList = arrWeek;
                }
            } else if (val === "按月") {
                startIdx = this.$moment(startTime).months();
                endIdx = this.$moment(endTime).months();
                let arrMonth = [
                    "一月",
                    "二月",
                    "三月",
                    "四月",
                    "五月",
                    "六月",
                    "七月",
                    "八月",
                    "九月",
                    "十月",
                    "十一月",
                    "十二月",
                ];
                for (let i = startIdx; i <= endIdx; i++) {
                    frequencyCycleList.push({
                        label: arrMonth[i],
                    });
                }
            } else {
                startIdx = this.$moment(startTime).years();
                endIdx = this.$moment(endTime).years();
                for (let i = startIdx; i <= endIdx; i++) {
                    frequencyCycleList.push({
                        label: i + "年",
                    });
                }
            }
            this.frequencyCycleList = frequencyCycleList;
        },
        // 切换选择
        handleRadio(val) {
            this.form.frequency2Day = "";
            this.form.frequency3Day = "";
            this.form.frequency2Week = "";
            this.form.frequency3Week = "";
            this.form.frequency4Week = "";
        },
        handleCommit(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.form.frequency != "按周") {
                        if (this.radioMouth === "day" || this.radioYear === "day") {
                            this.form.frequency2 = this.form.frequency2Day;
                            this.form.frequency3 = this.form.frequency3Day;
                        } else {
                            this.form.frequency2 = this.form.frequency2Week;
                            this.form.frequency3 = this.form.frequency3Week;
                            this.form.frequency4 = this.form.frequency4Week;
                        }
                    } else if (this.form.frequency == "按周") {
                        let frequency3 = [];
                        this.form.frequency3.map((d) => {
                            frequency3.push(d.val);
                        });
                        this.form.frequency3 = frequency3;
                    }
                    this.dataList.ppcgBlockDiagarmListDtlList.map((list) => {
                        if (list.id === this.form.masterId) {
                            list.ppcgBlockDiagarmDtlList.map((dtl) => {
                                if (dtl.id === this.form.id) {
                                    dtl.startTime = this.form.date[0];
                                    dtl.endTime = this.form.date[1];
                                    dtl.frequency1 = this.form.frequency;
                                    dtl.frequency2 = this.form.frequency2.toString();
                                    dtl.frequency3 = JSON.stringify(this.form.frequency3);
                                    dtl.frequency4 = this.form.frequency4;
                                    dtl.count = this.form.count;
                                }
                            });
                        }
                    });
                    let param = {
                        ppcgBlockDiagarm: this.dataList,
                    };
                    this.$axios
                        .post(`/form/formDefData/saveData?key=ppcgBlockDiagarm&sql=`, param)
                        .then((res) => {
                            if (res.isOk) {
                                this.dialogFormVisible = false;
                                this.$ElMessage({
                                    message: "保存成功",
                                    type: "success",
                                });
                                // this.goBack()
                            } else {
                                this.$ElMessage({
                                    message: res.msg,
                                    type: "error",
                                });
                            }
                        });
                }
            });
        },
    },
};
</script>

<style>
.card-margin {
    margin-top: 1rem;
}
.textAlign {
    text-align: left;
}
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}

.box-card {
    width: 20%;
}
.container {
    display: flex;
}
.cardItem {
    margin: 0 0.5rem;
}
.container {
    display: flex;
}
.cardItem {
    margin: 0 0.5rem;
}
</style>
